const {
	reqGet,
	reqPost,
} = require('@utils/request')
const {
	$U_UserInfo,
	$U_SetItem,
	$U_GetItem,
} = require('@utils/storage')
const {
	setFormEdit,
	setBtnEdit,
} = require('./api-utils');

/**
 * 初始化项目数据
 * @param  {[type]} apiComp   [description]
 * @param  {[type]} projectId [description]
 * @return {[type]}           [description]
 */
async function loadProjectData(apiComp, projectId, options) {
	let projectDataJSON = null;
	let userInfo = $U_UserInfo()
	let version = ''
	let project_data = ''
	let isLock = false
	let tmpApiDetail = null;
	let testServerUrl = '';
	let projectName = '';
	// 加载各版本数据
	if (options && options.project_data) {
		version = apiComp.store && apiComp.store.version || ''
		project_data = options.project_data
	} else {
		// 接口加载最新版本数据
		let project_result = await reqGet('/ult/api', {
			project_id: projectId,
		})
		let {
			id,
			name,
			is_locked,
			locked_user,
			test_server_url,
		} = project_result;
		projectName = name
		testServerUrl = test_server_url
		tmpApiDetail = apiComp.store && apiComp.store._currentCheckApiDetail || null
		project_data = project_result.project_data
		version = project_result.version
		isLock = locked_user.indexOf(userInfo.realname) > -1 && is_locked == 1 || false
	}
	project_data = project_data.replace(/^["'`]|["'`]$/g, '')
	try {
		projectDataJSON = JSON.parse(project_data)
		testServerUrl = projectDataJSON.testServerUrl = testServerUrl || projectDataJSON.testServerUrl
	} catch (e) {
		try {
			projectDataJSON = new Function(`return ${project_data};`)()
		} catch (e) {
			projectDataJSON = null
		}
		console.log('e', e)
		console.log('project_data', project_data)
	}
	console.log('projectDataJSON', projectDataJSON)
	if (!projectDataJSON || !projectDataJSON.tree || !projectDataJSON.apis) {
		$.messager.alert({
			title: '提示',
			msg: '参数加载错误！'
		})
		return false
	}
	apiComp.store = {
		version,
		projectId,
		projectName,
		// 原始项目数据
		orgProjectData: $.extend(true, {}, projectDataJSON),
		// 编辑项目数据
		editProjectData: $.extend(true, {}, projectDataJSON),
		// 项目锁定
		isLock,
		// 是否可以保存
		isSave: true,
		isTest: false,
		// 修改历史记录
		history: {},
		record: false,
		// 测试返回值
		tmpTestResponse: null,
		isHistoryVersion: false,
		_currentTreeNode: null,
		// 当前正在编辑的api信息(编辑状态)
		_currentEditApiDetail: null,
		// 当前选中的api信息
		_currentCheckApiDetail: null,
		_$modify: {},
		// req请求参数，res响应参数
		_flag: '',
		// 当前接口请求参数相关信息
		reqCurrent: {
			orgParameterList: null,
			editRow: null,
			parentRow: null,
			// 测试请求值对应参数
			editValueRow: null,
		},
		// 当前接口响应参数相关信息
		resCurrent: {
			orgParameterList: null,
			editRow: null,
			parentRow: null,
		},
	}

	// 初始化接口目录树
	let tree = $.extend(true, {}, projectDataJSON.tree)
	let treeData = []
	let firstApiId = 'api-00000000'
	parseTreeData(tree, treeData)
	console.log('treeData', treeData)
	apiComp.store._currentCheckApiDetail = tmpApiDetail || projectDataJSON.apis[firstApiId]
	apiComp.treeComp.tree('loadData', treeData)
	apiComp.testServerUrlComp.textbox('setValue', testServerUrl)
	loadAPIDetail(apiComp)
	setBtnEdit(apiComp)
	setFormEdit(apiComp)
	return apiComp
}

/**
 * 解析目录树结构
 * @param  {[type]} tree [description]
 * @return {[type]}      [description]
 */
function parseTreeData(tree, treeData, nodeId = 'module-00000000') {
	let node = tree[nodeId]
	while (node.attributes) {
		if (node.attributes.firstChildId) {
			node.state = node.id == 'module-00000000' ? 'open' : 'closed'
			node.children = []
			parseTreeData(tree, node.children, node.attributes.firstChildId)
		}
		treeData.push(node)
		if (!node.attributes.nextNodeId)
			break;
		node = tree[node.attributes.nextNodeId]
	}
	return treeData
}

/**
 * 加载接口详情信息
 * @param  {[type]} apiComp [description]
 * @param  {[type]} detail  [description]
 * @return {[type]}         [description]
 */
function loadAPIDetail(apiComp) {
	let {
		store,
		formComp,
		treeComp,
		reqParamsComp,
		resParamsComp,
	} = apiComp;
	let node = store._currentCheckApiDetail;
	let currentRequset = store.currentRequset;
	let currentResponse = store.currentResponse;
	let editProjectData = store.editProjectData;
	// api信息，从editProjectData中获取
	let detail = editProjectData.apis[node.id];
	// 当前编辑接口详情
	if (store.isLock)
		store._currentEditApiDetail = detail;
	else
		store._currentEditApiDetail = null;
	// 接口测试时使用的临时结果
	store.tmpResult = null
	let {
		id,
		name,
		contentType,
		path,
		method,
		intro,
		requestParameterList,
		responseParameterList,
	} = detail;
	console.log('requestParameterList', requestParameterList)
	console.log('responseParameterList', responseParameterList)

	// 加载详情信息时不记录变更历史
	store.record = false
	store.tmpTestResponse = null
	formComp.form('load', {
		id,
		name,
		contentType,
		path,
		method,
		intro,
	})
	try {
		requestParameterList = Array.isArray(requestParameterList) ? requestParameterList : JSON.parse(requestParameterList)
		responseParameterList = Array.isArray(responseParameterList) ? responseParameterList : JSON.parse(responseParameterList)
	} catch (e) {
		console.log('detail parameter json parse error ==> ', name, id, e)
		console.log('requestParameterList', requestParameterList)
		console.log('responseParameterList', responseParameterList)
		requestParameterList = []
		responseParameterList = []
	}
	reqParamsComp.treegrid('loadData', requestParameterList)
	resParamsComp.treegrid('loadData', responseParameterList)
	node = treeComp.tree('find', id)
	treeComp.tree('select', node.target)
}

module.exports = {

	loadProjectData,

	loadAPIDetail,

}